package cpm.lc.securitydemo.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录失败处理器
 */
@Component
public class IAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        response.setStatus(401);
        Map<String,Object> map = new HashMap<>();
        map.put("status",401);
        if (exception instanceof LockedException){
            map.put("msg","账户被锁定，登录失败，请联系管理员。");
        }else if (exception instanceof BadCredentialsException){
            map.put("msg","账户或密码错误，登录失败，请重新输入。");
        }else if (exception instanceof DisabledException){
            map.put("msg","账户被禁用，登录失败，请联系管理员。");
        }else if (exception instanceof AccountExpiredException){
            map.put("msg","帐户过期异常，登录失败。");
        }else if (exception instanceof CredentialsExpiredException){
            map.put("msg","凭证过期异常，登录失败。");
        }else {
            map.put("msg","登录失败");
        }
        ObjectMapper objectMapper = new ObjectMapper();
        writer.write(objectMapper.writeValueAsString(map));
        writer.flush();
        writer.close();
    }
}
